package es.hekorusoft.udpcache.messages;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.util.zip.GZIPOutputStream;

final class ByteBufferWriter {

	public static final void addByte(int value, ByteBuffer baos) {
		baos.put((byte) value);
	}

	public static final void addInt(int number, ByteBuffer baos) {
		baos.putInt(number);
	}

	public static final void addLong(long number, ByteBuffer baos) {
		baos.putLong(number);

	}

	public static final void addString(String str, ByteBuffer baos) throws IOException {
		byte[] strArray = str.getBytes();
		baos.putInt(strArray.length);
		baos.put(strArray);
	}

	public static final void addObject(Object obj, ByteBuffer baos) throws IOException {

		final byte[] data;

		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(ba);
		oos.writeObject(obj);
		oos.close();

		if (ba.size() > 60000) {
			System.out.println("Extra compression!");
			ByteArrayOutputStream gba = new ByteArrayOutputStream();
			GZIPOutputStream gos = new GZIPOutputStream(gba);
			gos.write(ba.toByteArray());
			gos.close();
			data = gba.toByteArray();
		} else {
			data = ba.toByteArray();
		}
		baos.putInt(data.length);
		baos.put(data);

	}

	public static final void addByteArray(byte[] array, ByteBuffer baos) throws IOException {
		baos.putInt(array.length);
		baos.put(array);
	}

}
